package cn.com.w.thread.demo.execute;


import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * <p>
 *     自定义的线程封装
 * </p>
 *
 * @author pojok
 * @version v1.0
 * @date 2021/8/27 11:23
 */
public class CustomRunnable<T,R> implements Runnable {

    /**
     * 处理器
     */
    private final Function<T, R> handler;

    /**
     * 执行完成后的回调
     */
    private BiConsumer<T,R> callBack;

    /**
     * 执行前调用
     */
    private Consumer<T> callBefore;

    /**
     * 待执行的任务信息封装
     */
    private final T param;

    public CustomRunnable(Function<T, R> handler, T param) {
        this.handler = handler;
        this.param = param;
    }

    public CustomRunnable(Function<T, R> handler, BiConsumer<T,R> callBack, T param) {
        this.handler = handler;
        this.callBack = callBack;
        this.param = param;
    }

    public CustomRunnable(Consumer<T> callBefore , Function<T, R> handler, BiConsumer<T,R> callBack, T param) {
        this.callBefore = callBefore;
        this.handler = handler;
        this.callBack = callBack;
        this.param = param;
    }

    @Override
    public void run() {
        R result = null;
        if (callBefore != null) {
            callBefore.accept(param);
        }
        try {
            result = handler.apply(param);
        } finally {
            if (callBack != null) {
                callBack.accept(param,result);
            }
        }
    }

}
